#include "script_engine.h"

namespace SkyID
{

//- ScriptEngine --------------------------------------------------------------

namespace ScriptEngine
{

static lua_State *gVM = NULL;

int ErrorHandler(lua_State *VM);
const char *HelperLuaRead(lua_State *VM, void *data, size_t *size);


bool initialize(const Config &config)
{
	gVM = luaL_newstate();
	luaL_openlibs(gVM);

	luabind::set_pcall_callback(&ErrorHandler);

	if (!LuabindExport::initialize(gVM))
		return false;

	LOG_MSG("ScriptEngine: initialized");
	return true;
}

void shutdown()
{
	LuabindExport::shutdown();

	lua_close(gVM);

	LOG_MSG("ScriptEngine: shutdown");
}

bool parseFile(const char *fileName)
{
	Reader *reader = VFS::getReader(fileName);
	if (!reader)
		return false;
	int result = lua_load(gVM, &HelperLuaRead, reader, fileName)
		|| lua_pcall(gVM, 0, LUA_MULTRET, 0);
	delete reader;
	if (result)
		ErrorHandler(gVM);
	return !result;
}

int ErrorHandler(lua_State *VM)
{
	lua_Debug d;
	lua_getstack(VM, 1, &d);
	lua_getinfo(VM, "Sln", &d);
	const char *error = lua_tostring(VM, -1);
	lua_pop(VM, 1);
	LOG_MSG("LUA error [%d] %s", d.currentline, error);
	if (d.name && *d.name)
		LOG_MSG("%s : %s", d.namewhat, d.name);
	return 0;
}

const char *HelperLuaRead(lua_State *VM, void *data, size_t *size)
{
	Reader *reader = reinterpret_cast<Reader*>(data);
	LOG_ASSERT(reader);
	size_t nsize = reader->size() - reader->tell();
	if (!nsize)
		return NULL;
	char *buffer = new char[nsize];
	if (reader->read(buffer, nsize) != nsize)
	{
		delete[] buffer;
		return NULL;
	}
	*size = nsize;
	return buffer;
}

/*
void setGlobal(const char *name, void *value, const char *type)
{
	//tolua_pushusertype(gVM, value, (char*)type);
	//lua_setglobal(gVM, name);
}

void callFunction(const char *functionName)
{
	//lua_getglobal(gVM, functionName);
	//lua_call(gVM, 0, 0);
}

void callFunction(const char *functionName, float dt)
{
	//lua_getglobal(gVM, functionName);
	//lua_pushnumber(gVM, dt);
	//lua_call(gVM, 1, 0);
}
*/

} // ScriptEngine

} // namespace SkyID
